package com.cosina.game.tank.model;

import java.util.Iterator;

import com.cosina.game.tank.Constants;
import com.cosina.game.tank.model.impl.EnemyTank;

public class UpdateEngine implements TimeElapse{

	private War war;
	public UpdateEngine(War war){
		this.war = war;
	}
	
	private void cleartDamageStatus(){
		
		for(Iterator<EnemyTank> iter = war.enemyTanks.iterator(); iter.hasNext();){
			EnemyTank eachEnemy = iter.next();
			eachEnemy.damage = false;
		}
		
		if(null != war.justiceTank){
			war.justiceTank.damage = false;
		}
	}
	@Override
	public void withTimeGo() {
		war.withTimeGo();
		
		cleartDamageStatus();
		
		if(war.justiceTank.damage){
			war.run = false;
		}else if(war.enemyTanks.size() == 0){
			war.run = false;
		}
		
		for(int i= war.pills.size()-1; i>=0; i--){
			Pill eachPill = war.pills.get(i);
			eachPill.withTimeGo();
			if(Constants.area.contains(eachPill.getX(), eachPill.getY()) == false){
				war.pills.remove(eachPill);
			}else if(eachPill.belongEnemy()){
				if(war.justiceTank.getBodyArea().contains(eachPill.getLocation().x,eachPill.getLocation().y)){
					war.justiceTank.damage();
					war.pills.remove(eachPill);
				}
			}else{
				for(EnemyTank eachEnemy :  war.enemyTanks){
					if(eachEnemy.getBodyArea().contains(eachPill.getLocation().x,eachPill.getLocation().y)){
						eachEnemy.damage();
						war.pills.remove(eachPill);
						break;
					}
				}
			}
		}
		
		for(Iterator<EnemyTank> iter = war.enemyTanks.iterator(); iter.hasNext();){
			EnemyTank eachEnemy = iter.next();
			if(eachEnemy.isSick()){
				eachEnemy.moreSick();
			}
		}
		
		if(war.justiceTank.isSick()){
			war.justiceTank.moreSick();
		}
		for(Iterator<EnemyTank> iter = war.enemyTanks.iterator(); iter.hasNext();){
			EnemyTank eachEnemy = iter.next();
			if(eachEnemy.isDead()){
				iter.remove();
			}
		}
		
		
		for(TimeElapse each :  war.enemyTanks){
			each.withTimeGo();
		}
	}
}
